package com.ww.boot.mybatis.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * 牛蛙数据库配置
 *
 * @author panyun
 * @date 2020/11/3 16:45
 */
@Configuration
@MapperScan(basePackages = "com.ww.boot.mybatis.mapper.pms", sqlSessionFactoryRef = "pmsSqlSessionFactory")
public class PmsDbConfig {
	@Bean(name = "pmsDataSource")
	@Primary
	@ConfigurationProperties(prefix = "spring.datasource.pms")
	public DataSource getDateSource2() {
		DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
		dataSource.setInitialSize(5);
		dataSource.setMaxActive(200);
		dataSource.setMinIdle(5);
		dataSource.setMaxWait(60000);
		dataSource.setValidationQuery("select 1");
		dataSource.setValidationQueryTimeout(2000);
		dataSource.setTestOnBorrow(false);
		dataSource.setTestOnReturn(false);
		return dataSource;
	}

	@Bean(name = "pmsSqlSessionFactory")
	@Primary
	public SqlSessionFactory test2SqlSessionFactory(@Qualifier("pmsDataSource") DataSource datasource,
													ObjectProvider<Interceptor[]> interceptorsProvider)
		throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(datasource);
		bean.setMapperLocations(
				new PathMatchingResourcePatternResolver().getResources("classpath*:com/ww/boot/mybatis/mapper/pms/*.xml"));
		return bean.getObject();
//		MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
//		bean.setDataSource(datasource);
//		bean.setPlugins(interceptorsProvider.getIfAvailable());
//		bean.setMapperLocations(
//			new PathMatchingResourcePatternResolver().getResources("classpath*:com/ww/boot/mybatis/mapper/pms/*.xml"));
//		return bean.getObject();
	}

	@Bean("pmsSqlSessionTemplate")
	@Primary
	public SqlSessionTemplate test2sqlsessiontemplate(
		@Qualifier("pmsSqlSessionFactory") SqlSessionFactory sessionfactory) {
		return new SqlSessionTemplate(sessionfactory);
	}
}
